<template>
  <div class="w100p bgf5f6">
    <!--搜索-->
    <div class="bgfff pl15 pb10 pr15">
      <div class="bgf5f6 bradius17 textc lh34 disflex align-cen pl25 search trans2 pr25"
           @click="search_focus">
        <img src="https://one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/user/search.png" style="flex: 0 0 16px" alt="" class="w16 h16">
        <span class="searchText over_1" v-if="!isfocus">{{searchkey || '搜索姓名/电话号码'}}</span>
        <input type="text" v-model="searchkey" placeholder="搜索姓名/电话号码"
               class="ca8 fs14 lh34 h34 textl pl10 w100p trans2"
               v-else
               :focus="isfocus"
               @blur="isfocus=false"
               @confirm="search_confirm">
      </div>
    </div>

    <div class="bgf5f6 pt15 pl16 pr15">
      <!--我的 / 默认 名片-->
      <div class="bradius10 bgfff " v-if="hasCard && card_msg.cardId">
        <GetPhoneNumber @next="toIndex('index', card_msg.companyId, card_msg.cardId)">
          <BusinessCard :card_msg="card_msg"
                        :type="'plus'"
                        :hasCard="hasCard"
                        :isdel="false"
                        :index="0"
                        @moreTap="moreTap">
          </BusinessCard>
        </GetPhoneNumber>
      </div>

      <!--看过的，名片-->

      <div v-if="lists.length>0">
        <div class="bradius10" v-for="(v,k) in lists" :key="k">
          <getPhoneNumberCard :card_msg="v"
                              :index="k+1"
                              @page_turn="toIndex"
                              @moreTap="moreTap"
          >
          </getPhoneNumberCard>
        </div>

      </div>

      <!--bottom-->
      <div class="textc lh70 fs12 ca8 bgf5f6" v-if="nodata">- 到底了，看看其他的吧 -</div>



      <!--创建-->

      <!--添加-->
      <div class="add_card">

        <!--        <div class="disflex overhidden jsbet bgblue trans2 bradius30 cfff fs18 lh60 pl21 pr22 mb10" @click="page_turn('editCard')"-->
        <!--             :class="addInfo ? 'h60' : 'h0' ">-->
        <!--          <div class="disflex align-cen">-->
        <!--            <img src="https://one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/user/add.png" alt="" class="w30 h30 mr11">-->
        <!--            <span>我的智能名片</span>-->
        <!--          </div>-->
        <!--          <span class="fbold ">立即创建</span>-->
        <!--        </div>-->


        <div class="textc disflex w60 h60 bgblue disinblock create-btn"
             @click="createCard"
             v-if="!hasCard"
             :class="addInfo ? 'w100p': ''"
        >
          <img src="https://one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/user/add.png"
               alt="" class="w30 h30 mr20">
          <span>我的智能名片</span>
          <div class="fbold create">
            立即创建
          </div>
        </div>
        <div class="textc disflex w60 h60 bradius50p bgblue disinblock" @click="page_turn('usercenter')" v-else>
          <img src="https://one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/user/user_add.png" alt="" class="w30 h30 mt15">
        </div>

      </div>


    </div>

    <SelectorOne
      :title="'操作'"
      :status="operateShow"
      :allClass="operateTypes"
      @closeModal="operateShow = !operateShow"
      @choose_tap="choose_tap"></SelectorOne>


    <!--初次登录-->

    <div v-if="!islogin" >
      <Login @GetUserInfo="GetUserInfo"
             @getPhoneNumber="getPhoneNumber"
             :isShow="!islogin"
             :phoneMsg="phoneMsg">
      </Login>
    </div>

  </div>


</template>

<script>
  import Login from '@/components/login' //
  import BusinessCard from '@/components/BusinessCard' //
  import SelectorOne from '@/components/selectorOne' //
  import GetPhoneNumber from '@/components/getPhoneNumber' //
  import getPhoneNumberCard from '@/components/getPhoneNumberCard' //
  import { mapActions } from 'vuex';

  import WXAJAX from '../../utils/request'
  import util from '../../utils/index'
  import websocket from '../../utils/websocket'

  export default {
    name: '',
    components: {Login,BusinessCard,SelectorOne, GetPhoneNumber, getPhoneNumberCard},
    data() {
      return {
        searchkey: '',
        last_searchkey: '',
        isfocus: false,
        mine_card:{},
        lists:[],
        hasCard:false ,//是否已经有名片
        islogin:true ,//是否已经登录
        wxCode:'',
        addInfo:false ,//显示添加的按钮
        loginMsg:{
          rawData : '' ,
          signature : '' ,
          encryptedData : '' ,
          iv : '' ,
        },
        card_msg: {
          picchecked: '',
          username: '',
          tel: '',
          wx: '',
          company_wx: '',
          email: '',
          post: '',
          company: '',
          company_logo: ''
        },
        phoneMsg:{
          phoneData:'',
          iv:'',
        },
        //名片操作
        operateID:0,
        operateShow:false,
        operateTypes:[
          {name:'置顶' , id:'top'},
          // {name:'删除' , id:'del'},
        ],
        cardId:0,//删除时使用
        isfresh:false ,
        page:1,
        isLoading : false ,//是否在加载
        nodata:false ,//是否已经没有数据
        isShowLogin: false,
      }
    },
    onReachBottom() {
      let v = this ;
      v.getAllCard();

    },
    onShareAppMessage(e){
      console.log(e)
      let cardId = e.target.dataset.cardid ;
      let companyId = e.target.dataset.companyid ;
      let companyName = e.target.dataset.companyname ;
      let name = e.target.dataset.name ;
      let position = e.target.dataset.position ;

      return {
        title : `您好，我是${companyName}${position || ''}的${name}，敬请惠存!`,
        path :'/pages/index/main?cardId='+cardId+'&companyId='+companyId +'&goType=1',
        success(e){
          console.log(e);
          wx.showShareMenu({
            withShareTicket : true
          })
        },
        fail(e){
          console.log('失败-- ',e);
        }
      }
    },
    onUnload(){
      this.isShowLogin = false;
    },
    async onPullDownRefresh() {
      // to doing..
      // 停止下拉刷新
      wx.showNavigationBarLoading();
      this.page = 1 ;
      this.card_msg = {} ;
      this.searchkey = '';
      this.lists = [] ;
      this.nodata = false ;
      this.isLoading = false ;
      this.getAllCard();
      wx.stopPullDownRefresh();
      setTimeout(function () {
        wx.hideNavigationBarLoading();
      },300)
    },
    onShow() {
      this.searchkey = '';
      this.isfresh = true ;
      this.card_msg = {} ;
      this.page = 1 ;
      this.islogin = true;
      this.hasCard = wx.getStorageSync('hasCard');
      /*获取登录信息*/

      //登录
      var v = this;

      wx.showLoading() ;
      if(wx.getStorageSync('token')){
        this.getAllCard();
      }else{
        v.islogin = false ;
        this.getLoginStatus();
      }
      this.loginMsg = wx.getStorageSync('loginMsg');
      wx.hideLoading();

      setTimeout(()=>{
        this.isShowLogin=true;
      }, 100);

      wx.setNavigationBarTitle({
        title: '名片夹'
      });
    },

    onHide(){
      this.addInfo = false;
    },
    methods: {
      ...mapActions(['setPhone']),
      shareApp(companyId,cardId, companyName, name){
        this.onShareAppMessage(companyId,cardId, companyName, name)
      },
      createCard(){
        util.toMiniProgram('/pages/editCard/main?goType=1&type=add');
      },
      search_focus() {
        this.isfocus = true;
      },
      search_confirm() {
        if (this.searchkey == this.last_searchkey) {
          return;
        }
        wx.showLoading() ;
        this.page = 1 ;
        this.card_msg = {} ;
        this.lists = [] ;
        this.nodata = false ;
        this.isLoading = false ;
        this.getAllCard();
      },
      page_turn(url){
        // wx.clearStorageSync('choose_company');
        // wx.clearStorageSync('choose_company_id');
        this.addInfo = false ;
        wx.navigateTo({url:'../'+url+'/main'})
      } ,
      toIndex(url,companyid,cardid){//进入首页
        wx.setStorageSync('COMPANYID',companyid);/*id*/
        wx.setStorageSync('CARDID',cardid);/*id*/
        this.addInfo = false ;
        wx.switchTab({url:'../'+url+'/main?cardId='+cardid+'&companyId+'+companyid});
      },
      getLoginStatus(){
        let v = this ;
        console.log('loginnnnnnnnnnnnnnnn');
        wx.login({
          success: (data) => {
            wx.hideLoading();
            if (data.code) {
              //保存code
              v.wxCode = data.code;
              // v.login() ;
            } else {
              wx.showToast({
                title: '获取登录态失败！',
                duration: 2000,
                icon: 'none'
              });
              // console.log('获取用户登录态失败！' + data.errMsg)
            }
          },
          fail(res) {
            wx.hideLoading() ;
          }

        });
      },
      getPhoneNumber(e) {
        this.phoneMsg.phoneData = e.encryptedData ;
        this.phoneMsg.iv = e.iv ;
      },
      GetUserInfo(msg){//获取用户信息
        this.loginMsg = {
          rawData : msg.rawData ,
          signature : msg.signature ,
          encryptedData : msg.encryptedData ,
          iv : msg.iv ,
        };
        // this.getLoginStatus();
        this.login() ;
      },
      login(msg){
        wx.showLoading() ;
        WXAJAX.POST({
          code: this.wxCode,
          rawData:this.loginMsg.rawData,
          signature : this.loginMsg.signature,
          encrypteData : this.loginMsg.encryptedData,
          iv:this.loginMsg.iv,
          phoneData:this.phoneMsg.phoneData ,
          phoneIv : this.phoneMsg.iv ,
        },'','/home/wxLogin').then((data) => {

          console.log("登录成功返回信息",data)
          wx.setStorageSync('loginMsg',this.loginMsg)
          if(data.token){
            wx.setStorageSync('token', data.token);
            wx.setStorageSync('avatarUrl' , data.avatarUrl) ;
            wx.setStorageSync('USERNAME',data.userName) ;
            wx.setStorageSync('phone',data.phone) ;
            wx.setStorageSync('userId',data.userId);
            wx.setStorageSync('hasCard', data.cardId != 0);
            this.setPhone(data.phone);
            this.hasCard = data.cardId != 0;
            this.islogin = true ;
            let url = wx.getStorageSync('redirectPage');
            websocket.connect(101);

            if(url){
              setTimeout(()=>{
                wx.removeStorageSync('redirectPage');
                wx.reLaunch({url: url});
              }, 1*1000);
            }else{
              this.isLoading = false;
              //获取所有的名片
              // this.getLoginStatus();
              this.getAllCard();
            }
          }

        }).catch((err) => {
          this.getLoginStatus();
          wx.hideLoading();
        });
      },
      getAllCard(){

        let v = this ;
        if(v.isLoading){
          return
        }
        v.isLoading = true ;
        WXAJAX.POST({
          name : this.searchkey ,
          pageNum: v.page ,
        },'','/businessCard/seeDetail','1').then((data) => {
          this.last_searchkey = this.searchkey ;
          // state : 1 -- 默认 ， 2 -- 浏览记录 ， 3 -- 自己的
          if(data){
            this.lists = [] ;
            let datas = [] ;
            data.forEach(function (i,k) {
              if( i.state == 3){//默认名片

                v.card_msg = {
                  picchecked: i.logo || '',
                  username: i.name || '',
                  tel: i.phone || '',
                  wx: i.personalWx || '',
                  company_wx: i.companyWx || '',
                  email: i.email || '',
                  post: i.position || '',
                  company: i.companyName,
                  company_logo: i.companyLogo ,
                  cardId : i.cardId,
                  companyId:i.companyId ,
                  recordId:i.recordId
                };

              }else{
                v.lists.push({
                  picchecked: i.logo || '',
                  username: i.name || '',
                  tel: i.phone || '',
                  wx: i.personalWx || '',
                  company_wx: i.companyWx || '',
                  email: i.email || '',
                  post: i.position || '',
                  company: i.companyName,
                  company_logo: i.companyLogo,
                  createTime:util.getdate(i.createTime , 'dateTime'),
                  cardId : i.cardId,
                  companyId:i.companyId ,
                  recordId : i.recordId
                });
              }
            });

            v.page ++ ;

            if(!v.hasCard){
              v.addInfo = true;
            }
          }
          setTimeout(function () {
            v.nodata = true ;
            v.isLoading = false ;
          },500);

          wx.hideLoading();
        }).catch((err) => {
          wx.hideLoading();
          if(err.code == 204){
            v.nodata = true ;
          }

          if (err.code == 401) {
            v.islogin = false;
            this.getLoginStatus();
          }

        });


      },
      moreTap(recordId,cardId , isdel ){//更多操作
        this.operateID = recordId ;
        this.cardId = cardId ;
        if(isdel){
          this.operateTypes = [
            {name:'置顶' , id:'top'},
            // {name:'删除' , id:'del'},
          ];
        }else{
          this.operateTypes = [
            {name:'置顶' , id:'top'},
          ];
        }
        this.operateShow = true ;
      },
      choose_tap(type){//名片操作
        this.operateShow = false ;

        wx.showLoading();

        let _url = '' ,
          id = 0 ;
        if(type == 'top'){
          _url = '/businessCard/isTop' ;
          id = this.cardId ;
        }else{
          _url = '/businessCard/delSeeCard' ;
          id = this.cardId ;
        }

        WXAJAX.POST({
          cardId : id
        },'',_url ,).then((data) => {

          wx.hideLoading();
          wx.showToast({
            title: '操作成功！',
            duration: 2000,
            icon: 'none'
          });
          this.getAllCard() ;

        }).catch((err) => {
          wx.hideLoading();
        });

      }
    }
  }
</script>

<style>
  .searchText{
    cursor:auto;
    display:inline-block;
    height:34px;
    max-width:100%;
    padding-left:10px;
    text-align:left;
    line-height:34px;
    font-size:14px;
    color:#A8A8A8;

  }
  .search {
    justify-content: center
  }

  .search.focus {
    justify-content: flex-start;
  }

  .search.focus input {
    width: auto;
  }
  page{
    width: 100%;
    height: 100%;
  }
  .add_card{
    width: 100%;
    position: fixed;
    right: 0;
    bottom: 45px;
    z-index: 99;
    padding-right: 15px;
    padding-left: 15px;
    box-sizing: border-box;
    text-align: right;
  }

  .create-btn{
    transition: all .8s ease-in-out;
    display:inline-flex;
    align-items:center;
    box-sizing: border-box;
    padding: 0 15px;
    border-radius: 999px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    color: white;
    position: relative;
  }
  .create-btn .create{
    flex-grow: 1;
    text-align: right;
  }

  .width-max{
    width: 100%;
  }

  .create-btn img{
    flex:0 0 30px ;
  }
</style>


